package com.enjoy.xbase.qk.cookie;


import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Locale;


/**
 * 序号化工具类
 */
public class SerializableUtil {

    /**
     * cookies 序列化成 string
     *
     * @param data 要序列化
     * @return 序列化之后的string
     */
    public static String objectToString(Object data) {
        if (data == null) return null;
        byte[] bytesData = objectToBytes(data);
        if (bytesData == null) return null;
        return byteArrayToHexString(bytesData);
    }

    public static byte[] objectToBytes(Object data) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(data);
        } catch (IOException e) {
            Log.i("objectToBytes: ", e.toString());
            return null;
        }
        return os.toByteArray();
    }

    /**
     * 将字符串反序列化成cookies
     *
     * @param cookieString cookies string
     * @return cookie object
     */
    public static <T> T decodeObject(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        return bytesToObject(bytes);
    }

    public static <T> T bytesToObject(byte[] bytes) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return (T) objectInputStream.readObject();
        } catch (Exception e) {
            Log.i("bytesToCookie: ", e.toString());
        }
        return null;
    }


    /**
     * 二进制数组转十六进制字符串
     *
     * @param bytes byte array to be converted
     * @return string containing hex values
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }

    /**
     * 十六进制字符串转二进制数组
     *
     * @param hexString string of hex-encoded values
     * @return decoded byte array
     */
    private static byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

}
